﻿using System;
using System.Collections.Generic;
using ProductCollector.com.ebay.developer;

namespace ProductCollector {
    public class EbaySearcher : ISiteSearcher {
        public IList<Product> Search(SearchCriteria criteria) {
            List<Product> pResults = new List<Product>();
            try {
                // Creating an object to the BestMatchService class
                EbayFindingService service = new EbayFindingService();
                service.Url = "http://svcs.ebay.com/services/search/FindingService/v1";

                // Creating request object for FindBestMatchItemDetailsByKeywords API
                FindItemsByKeywordsRequest request = new FindItemsByKeywordsRequest();
                // Setting the required property values
                request.keywords = criteria.SearchValue;

                // Setting the pagination
                var pagination = new PaginationInput();
                pagination.entriesPerPageSpecified = true;
                pagination.entriesPerPage = criteria.NumOfProduct;
                pagination.pageNumberSpecified = true;
                pagination.pageNumber = criteria.CurrentPageIndex;
                request.paginationInput = pagination;

                // Creating response object
                FindItemsByKeywordsResponse response = service.findItemsByKeywords(request);
                SearchResult result = response.searchResult;
                // Console.WriteLine("Find items results");

                // Looping through response object for result
                if (result.item != null) {
                    foreach (SearchItem item in result.item) {
                        Product p = new Product() {
                            ProductName = item.itemId,
                            Price = item.sellingStatus != null? (float)item.sellingStatus.currentPrice.Value: 0,
                            FormattedPrice = item.sellingStatus != null ? item.sellingStatus.currentPrice.Value.ToString() + " "+item.sellingStatus.currentPrice.currencyId : string.Empty,
                            Description = item.title,
                            OriginalUrl = item.viewItemURL,
                            ThumbImg = item.galleryURL?? item.pictureURLLarge?? item.pictureURLSuperSize,
                            //Stock = item. // TODO add stock value
                        };
                        pResults.Add(p);
                    }
                }
            } catch {

            }
            return pResults;
        }

        public int CountProduct(SearchCriteria criteria) {
            throw new NotImplementedException();
        }
    }
}
